//
//  YDNetworkServerManager.swift
//  YDPerfectServer
//
//  Created by rowena on 2019/7/31.
//

import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
import Foundation


open class YDNetworkServerManage {

    fileprivate var server: HTTPServer
    
    let userDatabase: YDUserDatabase = YDUserDatabase()
    
    
//    internal init(root: String, port: UInt16) {
//
//        server = HTTPServer.init()                          //创建HTTPServer服务器
//        var routes = Routes.init(baseUri: "/")           //创建路由器
//        configure(routes: &routes)                          //注册路由
//        server.serverName = "localhost"
//        server.addRoutes(routes)                            //路由添加进服务
//        server.serverPort = port                            //端口
//        server.documentRoot = root                          //根目录
//        server.serverAddress = "39.97.250.51"
//        server.setResponseFilters([(Filter404(), .high)])   //404过滤
//
//    }
    
    
    internal init(root: String, port: UInt16) {
        
        server = HTTPServer.init()                          //创建HTTPServer服务器
        var routes = Routes.init(baseUri: "/")           //创建路由器
        configure(routes: &routes)                          //注册路由
        server.serverName = "localhost"
        server.addRoutes(routes)                            //路由添加进服务
        server.serverPort = port                            //端口
        server.documentRoot = root                          //根目录
        server.setResponseFilters([(Filter404(), .high)])   //404过滤
        
    }
    
    //MARK: 开启服务
    open func startServer() {
        
        do {
            print("启动HTTP服务器")
            try server.start()
        } catch PerfectError.networkError(let err, let msg) {
            print("网络出现错误：\(err) \(msg)")
        } catch {
            print("网络未知错误")
        }
        
    }
    
    //MARK: 注册路由
    fileprivate func configure(routes: inout Routes) {

        // 添加接口,请求方式,路径
        routes.add(method: .get, uri: "/") { (request, response) in
            
            response.setHeader(.contentType, value: "text/html")
            
            response.appendBody(string: "<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>允顶科技</title><body>允顶科技有限公司欢迎您！</body></html>")
            .completed()
            
            
//            response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
//                .completed()
            
//            response.setHeader( .contentType, value: "application/json")          //响应头
//
//            let jsonString = YDDataFormatManager.baseResponseBodyJSONData(code: 0, message: "成功", data: nil)
//            response.setBody(string: jsonString)                           //响应体
//            response.completed()                                           //响应
        }
        // 添加接口,请求方式,路径,登录接口
        routes.add(method: .post, uri: "/login") { (request, response) in
            //创建用户数据管理类
            let userDataManager: YDUserDataManager = YDUserDataManager()
            //解析传递后的参数
            let dict: [String: Any] = YDDataFormatManager.dictForRequest(request: request)
            let jsonString = userDataManager.userDataManagerWithLogin(parameters: dict)
            
            //网络请求响应设置
            response.setHeader( .contentType, value: "application/json")            //响应头
            response.setBody(string: jsonString)                                    //响应体
            response.completed()                                                    //响应
        }
        
        // 添加接口,请求方式,路径,注册接口
        routes.add(method: .post, uri: "/register") { (request, response) in
            //创建用户数据管理类
            let userDataManager: YDUserDataManager = YDUserDataManager()
            //解析传递后的参数
            let dict: [String: Any] = YDDataFormatManager.dictForRequest(request: request)
            let jsonString = userDataManager.userDataManagerWithRegister(parameters: dict)
            
            //网络请求响应设置
            response.setHeader( .contentType, value: "application/json")            //响应头
            response.setBody(string: jsonString)                                    //响应体
            response.completed()
        }
    }
    
    //MARK: 404过滤
    struct Filter404: HTTPResponseFilter {
        
        func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
            callback(.continue)
        }
        
        func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
            if case .notFound = response.status {
                response.setBody(string: "404 文件\(response.request.path)不存在。")
                response.setHeader(.contentLength, value: "\(response.bodyBytes.count)")
                callback(.done)
                
            } else {
                callback(.continue)
            }
        }
        
    }
    
}
